package src.CodeTopSecondPractice;

public class _142 {
    public ListNode detectCycle(ListNode head) {
        if (head == null)
            return null;
        boolean flag = false;
        ListNode fast = head, slow = head;
        while (slow.next != null && fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                flag = true;
                break;
            }
        }
        if (flag) {
            slow = head;
            while (slow != fast) {
                slow = slow.next;
                fast = fast.next;
            }
            return fast;
        }
        return null;
    }
}
